package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.OrderSetting;
import com.itheima.service.OrdersettingService;
import com.itheima.utils.POIUtils;
import com.itheima.utils.POIUtils2;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/ordersetting")
public class OrdersettingController {
   @Reference
   private OrdersettingService ordersettingService;

   /**
    * 解析excel文件,将数据保存到数据库
    * @param excelFile
    * @return
    */
   @RequestMapping("/upload")
   public Result upload(MultipartFile excelFile) {
      try {
         //1.调用POI工具类
         List<String[]> list = POIUtils.readExcel(excelFile);
         if (list != null && list.size() > 0) {
            //2.重新封装list集合
            List<OrderSetting> dataList = new ArrayList<OrderSetting>();
            String dateString = "";
            String numString = "";
            for (String[] strings : list) {
               dateString = strings[0];
               numString = strings[1];
               dataList.add(new OrderSetting(new Date(dateString),Integer.parseInt(numString)));
            }
            //3.调用服务进行添加
            ordersettingService.add(dataList);
         }

      } catch (IOException e) {
         e.printStackTrace();
         return new Result(false, MessageConstant.IMPORT_ORDERSETTING_FAIL);//上传失败
      }
      return new Result(true,MessageConstant.IMPORT_ORDERSETTING_SUCCESS);//上传成功
   }

   /**
    * 获取当前月份所有预约设置信息
    * @param date
    * @return
    */
   @RequestMapping("/getOrdersettingByMonth/{date}")
   public Result getOrdersettingByMonth(@PathVariable String date) {
      try {
         //调用服务查询数据
         List<Map> list = ordersettingService.getOrdersettingByMonth(date);
         return new Result(true,MessageConstant.GET_ORDERSETTING_SUCCESS,list);//上传成功
      } catch (Exception e) {
         e.printStackTrace();
         return new Result(false, MessageConstant.GET_ORDERSETTING_FAIL);//上传失败
      }

   }

   @RequestMapping("/editNumberByDate")
   public Result editNumberByDate(@RequestBody OrderSetting orderSetting) {
      try {
         //调用服务之星编辑操作
         ordersettingService.editNumberByDate(orderSetting);
         return new Result(true,MessageConstant.ORDERSETTING_SUCCESS);//预约设置成功
      } catch (Exception e) {
         e.printStackTrace();
         return new Result(false, MessageConstant.ORDERSETTING_FAIL);//预约设置失败
      }

   }
}
